//
//  KAKeyboardInputView.swift
//  kano
//
//  Created by Frank on 2025/5/20.
//

import UIKit
import SnapKit

class KAKeyboardInputView: UIView {
    // MARK: - Properties
    private var currentCount: Int = 0
    private var keyBoardHeight: CGFloat = 0
    private var defaultContent: String?
    private var contentChangedNum: Int = 0
    
    var title: String = "" {
        didSet { titleLabel.text = title }
    }
    
    var contentPlaceHolder: String = "" {
        didSet {
            textView.setPlaceholder(text: contentPlaceHolder, color: .placeholderGray)
        }
    }
    
    var maxInputLength: Int = 0 {
        didSet { updateCountLabel() }
    }
    
    var contentText: String = "" {
        didSet {
            textView.placeholderLabel.isHidden = !contentText.isEmpty
            if contentChangedNum == 0 {
                defaultContent = contentText
            }
            textView.text = contentText
            currentCount = contentText.count
            updateCountLabel()
        }
    }
    
    var doneTitle: String = "Complete" {
        didSet {
            doneButton.setTitle(doneTitle, for: .normal)
            doneButton.setTitle(doneTitle, for: .selected)
        }
    }
    
    var inputTextEndBlock: ((String) -> Void)?
    
    // MARK: - UI Components
//    private lazy var backgroundView: UIVisualEffectView = {
//        let effect = UIBlurEffect(style: .light)
//        let view = UIVisualEffectView(effect: effect)
//        view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
//        view.frame = self.bounds;
//        view.isUserInteractionEnabled = true;
//        let tap = UITapGestureRecognizer(target: self, action: #selector(dismiss))
//        view.addGestureRecognizer(tap)
//        return view
//    }()
    
    lazy var backgroundView: UIView = {
        let var_backgroundView = UIVisualEffectView(frame: bounds)
        var_backgroundView.frame = bounds
        var_backgroundView.backgroundColor = UIColor.ka_hexColor(0x000000, alphaVaule: 0.66)
        var_backgroundView.isUserInteractionEnabled = true;
        let tap = UITapGestureRecognizer(target: self, action: #selector(dismiss))
        var_backgroundView.addGestureRecognizer(tap)
        return var_backgroundView
    }()
    
    private lazy var shadowView: UIView = {
        let view = UIView()
        view.layer.shadowColor = UIColor(white: 0, alpha: 0.1).cgColor
        view.layer.shadowOffset = .zero
        view.layer.shadowRadius = 23
        view.layer.shadowOpacity = 1
        return view
    }()
    
    private lazy var keyBoardView: UIView = {
        let view = UIView()
        view.backgroundColor = .white
        return view
    }()
    
    private lazy var titleLabel: UILabel = {
        let label = UILabel()
        label.font = .boldSystemFont(ofSize: 18)
        label.textColor = .black
        return label
    }()
    
    private(set) lazy var textView: UITextView = {
        let tv = UITextView()
        tv.font = .systemFont(ofSize: 14)
        tv.textColor = .black
        tv.delegate = self
        return tv
    }()
    
    private lazy var countLabel: UILabel = {
        let label = UILabel()
        label.font = .systemFont(ofSize: 13)
        label.textColor = .systemBlue
        return label
    }()
    
    private lazy var closeButton: UIButton = {
        let btn = UIButton(type: .custom)
        btn.setImage(UIImage(named: "input_close"), for: .normal)
        btn.addTarget(self, action: #selector(closeAction), for: .touchUpInside)
        return btn
    }()
    
    private lazy var doneButton: UIButton = {
        let btn = UIButton(type: .custom)
        btn.titleLabel?.font = .boldSystemFont(ofSize: 16)
        btn.setTitleColor(.white, for: .normal)
        btn.setTitle("Confirm", for: .normal)
        btn.backgroundColor = .themeColor
        btn.layer.cornerRadius = 5
        btn.layer.shadowColor = UIColor.systemBlue.withAlphaComponent(0.3).cgColor
        btn.layer.shadowOffset = CGSize(width: 0, height: 5)
        btn.layer.shadowOpacity = 1
        btn.layer.shadowRadius = 9
        btn.addTarget(self, action: #selector(sendAction), for: .touchUpInside)
        return btn
    }()
    
    // MARK: - Lifecycle
    override init(frame: CGRect) {
        super.init(frame: UIScreen.main.bounds)
        setupUI()
        setupNotifications()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setupUI()
        setupNotifications()
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    // MARK: - Setup
    private func setupUI() {
        let screenSize: CGSize = UIScreen.main.bounds.size
        addSubview(backgroundView)
        
        self.shadowView.frame = CGRect(x: 0, y: screenSize.height - 247, width: screenSize.width, height: 247);
        addSubview(shadowView)
        
        self.keyBoardView.frame = self.shadowView.bounds;
        shadowView.addSubview(keyBoardView)
        
        
        let maskPath = UIBezierPath(
            roundedRect: keyBoardView.bounds,
            byRoundingCorners: [.topLeft, .topRight],
            cornerRadii: CGSize(width: 13, height: 13)
        )
        let maskLayer = CAShapeLayer()
        maskLayer.frame = keyBoardView.bounds
        maskLayer.path = maskPath.cgPath
        keyBoardView.layer.mask = maskLayer
        
        keyBoardView.addSubview(titleLabel)
        keyBoardView.addSubview(textView)
        keyBoardView.addSubview(closeButton)
        keyBoardView.addSubview(doneButton)
        keyBoardView.addSubview(countLabel)
        
        let lineView = UIView()
        lineView.backgroundColor = UIColor(red: 221/255, green: 221/255, blue: 221/255, alpha: 1)
        keyBoardView.addSubview(lineView)
        
        setupConstraints(lineView: lineView)
    }
    
    private func setupConstraints(lineView: UIView) {
        
        lineView.snp.makeConstraints {
            $0.left.right.equalToSuperview().inset(20)
            $0.height.equalTo(1/UIScreen.main.scale)
            $0.bottom.equalTo(doneButton.snp.top).offset(-20)
        }
        
        titleLabel.snp.makeConstraints {
            $0.top.left.equalTo(20)
        }
        
        textView.snp.makeConstraints {
            $0.left.equalTo(titleLabel)
            $0.top.equalTo(titleLabel.snp.bottom).offset(30)
            $0.right.equalTo(-20)
            $0.bottom.equalTo(countLabel.snp.top).offset(-6)
        }
        
        closeButton.snp.makeConstraints {
            $0.size.equalTo(40)
            $0.top.right.equalToSuperview().inset(6.5)
        }
        
        doneButton.snp.makeConstraints {
            $0.left.right.equalToSuperview().inset(20)
            $0.bottom.equalTo(-15)
            $0.height.equalTo(45)
        }
        
        countLabel.snp.makeConstraints {
            $0.right.equalTo(-20)
            $0.bottom.equalTo(lineView.snp.top).offset(-20)
        }
    }
    
    private func setupNotifications() {
        NotificationCenter.default.addObserver(
            self,
            selector: #selector(keyboardDidShow(_:)),
            name: UIResponder.keyboardWillShowNotification,
            object: nil
        )
        
        NotificationCenter.default.addObserver(
            self,
            selector: #selector(keyboardDidHidden(_:)),
            name: UIResponder.keyboardWillHideNotification,
            object: nil
        )
        
        NotificationCenter.default.addObserver(
            self,
            selector: #selector(textChanged(_:)),
            name: UITextView.textDidChangeNotification,
            object: textView
        )
    }
    
    // MARK: - Actions
    @objc private func sendAction() {
        let value = textView.text ?? ""
//        guard value != defaultContent else {
//            dismiss()
//            return
//        }
        
        dismiss()
        inputTextEndBlock?(value)
    }
    
    @objc private func closeAction() {
        dismiss()
    }
    
    @objc func dismiss() {
        endEditing(true)
        UIView.animate(withDuration: 0.25) {
            self.alpha = 0
        } completion: { _ in
            self.removeFromSuperview()
        }
    }
    
    // MARK: - Keyboard Handling
    @objc private func keyboardDidShow(_ notification: Notification) {
        guard let info = notification.userInfo,
              let keyboardFrame = info[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect else { return }
        
        keyBoardHeight = keyboardFrame.height
        UIView.animate(withDuration: info[UIResponder.keyboardAnimationDurationUserInfoKey] as? TimeInterval ?? 0.25) {
            self.shadowView.transform = CGAffineTransform(translationX: 0, y: -keyboardFrame.height)
        }
    }
    
    @objc private func keyboardDidHidden(_ notification: Notification) {
        UIView.animate(withDuration: notification.userInfo?[UIResponder.keyboardAnimationDurationUserInfoKey] as? TimeInterval ?? 0.25) {
            self.shadowView.transform = .identity
        }
    }
    
    // MARK: - Text Handling
    @objc private func textChanged(_ notification: Notification) {
        currentCount = textView.text.count
        updateCountLabel()
        textView.placeholderLabel.isHidden = currentCount > 0 ? true : false
    }
    
    private func updateCountLabel() {
        let (text, shouldWarn) = formatCount(current: currentCount, total: maxInputLength)
        countLabel.text = text
        countLabel.textColor = shouldWarn ? .red : .systemBlue
        
        if shouldWarn {
            textView.text = String(textView.text.prefix(maxInputLength))
            currentCount = maxInputLength
        }
    }
    
    private func formatCount(current: Int, total: Int) -> (String, Bool) {
        guard total > 0 else { return ("", false) }
        let displayCount = min(current, total)
        return ("\(displayCount)/\(total)", current > total)
    }
}

// MARK: - UITextViewDelegate
extension KAKeyboardInputView: UITextViewDelegate {
    func textViewDidChange(_ textView: UITextView) {
        contentChangedNum += 1
        currentCount = textView.text.count
        updateCountLabel()
    }
}

// MARK: - Presentation
extension KAKeyboardInputView {
    func show() {
        guard let window = UIApplication.shared.keyWindow else { return }
        
        window.addSubview(self)
        textView.becomeFirstResponder()
        
        backgroundView.alpha = 0
        UIView.animate(withDuration: 0.25, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 1) {
            self.backgroundView.alpha = 1
        }
    }
}

// MARK: - Color Extensions
extension UIColor {
    static let placeholderGray = UIColor(red: 204/255, green: 204/255, blue: 204/255, alpha: 1)
}
